<template lang="">
    <div>
        <el-dialog @opened="cateEdit" :before-close="cancel" center :title="isAdd ? '添加商品管理' : '修改商品管理'"  :visible.sync="isShow">
       <el-form :model="goodsForm" :rules="rules" ref="goodsForm" label-width="100px" class="demo-goodsForm">
        <el-form-item label="一级分类" prop="first_cateid">
    <el-select  v-model="goodsForm.first_cateid"
              @change="changeCate(false)"
              placeholder="请选择">
      <el-option    v-for="item in catelist"
              :value="item.id"
              :key="item.id"
              :label="item.catename" ></el-option>
    </el-select>
  </el-form-item>
        <el-form-item label="二级分类" prop="second_cateid">
    <el-select v-model="goodsForm.second_cateid" placeholder="请选择">
      <el-option v-for ="item in secondArr" 
            :value="item.id"
            :key="item.id"
            :label="item.catename"></el-option>
    </el-select>
  </el-form-item>
    <el-form-item label="商品名称" prop="goodsname">
    <el-input v-model="goodsForm.goodsname" autocomplete="off"></el-input>
  </el-form-item>
    <el-form-item label="商品价格" prop="price">
    <el-input v-model="goodsForm.price" autocomplete="off"></el-input>
  </el-form-item>
   <el-form-item label="市场价格" prop="market_price">
    <el-input v-model="goodsForm.market_price"  autocomplete="off"></el-input>
  </el-form-item>
      <el-form-item label="图片" :label-width="formLabelWidth">
          <el-upload
            action="#"
            list-type="picture-card"
            :on-preview="onPreview"
            :on-remove="handleRemove"
            :auto-upload="false"
            :on-change="onChange"
            :file-list="fileList"
            :limit="1"
            :on-exceed="onExceed"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="" />
          </el-dialog>
        </el-form-item>
            <el-form-item label="商品规格" prop="specsid">
    <el-select v-model="goodsForm.specsid" 
              @change="changeSpecs(false)"
               placeholder="请选择">
      <el-option v-for="item in specslist"
                 :label="item.specsname" 
                 :value="item.id"
                 :key="item.id"></el-option>
     
    </el-select>
  </el-form-item>
        <el-form-item label="规格属性" prop="specsattr">
               <!-- multiple 是否多选 -->
    <el-select v-model="goodsForm.specsattr"  multiple placeholder="请选择">
      <el-option    v-for="item in specsArr"
              :value="item"
              :key="item"
              :label="item"></el-option>
    </el-select>
  </el-form-item>
  <el-form-item label="是否新品">
      <el-radio v-model="goodsForm.isnew" :label="1">是</el-radio>
  <el-radio v-model="goodsForm.isnew" :label="2">否</el-radio>
  </el-form-item>
  <el-form-item label="是否热卖">
      <el-radio v-model="goodsForm.ishot" :label="1">是</el-radio>
  <el-radio v-model="goodsForm.ishot" :label="2">否</el-radio>
  </el-form-item>
   <el-form-item label="商品描述">
   <div id="edit"></div>
   </el-form-item>
          <el-form-item  label="状态">
   <el-switch
    v-model="goodsForm.status"
    active-color="#13ce66"
    inactive-color="#ff4949"
    :active-value="1"
    :inactive-value="2">
  </el-switch>
</el-form-item>
</el-form>
  <div slot="footer" class="dialog-footer">
    <el-button @click="cancel">取 消</el-button>
    <el-button type="primary"  @click="confirm">确 定</el-button>
  </div>
  </el-dialog>
 
    </div>
</template>
<script>
import { goodsAdd, goodsInfo, goodsEdit } from '../../request/api'
import { mapGetters, mapActions } from 'vuex';
//局部引入wangEditor
import wangEditor from 'wangeditor'
export default {
  props: ['isShow', 'isAdd'],
  data() {
    return {
      goodsForm: {
        first_cateid: "", //一级分类编号
        second_cateid: "", //二级分类编号
        goodsname: "", //商品名称
        price: "", //商品价格
        market_price: "", //市场价格
        img: "", //商品图片（文件）
        description: "", //商品描述
        specsid: "", //商品规格编号
        specsattr: "", //商品规格属性
        isnew: 1, //是否新品1是2不是
        ishot: 1, //是否热卖1是2不是
        status: 1, //状态1正常2禁用
      },
      formLabelWidth: "120px", //label宽度
      //dialogVisible 用于控制图片预览的显示隐藏
      dialogVisible: false,
      //预览时调用的图片地址
      dialogImageUrl: "",
      fileList: [], //用于图片回显
      //规则验证
      rules: {
        goodsname: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
          {
            min: 2,
            max: 15,
            message: "长度在 2 到 15 个字符",
            trigger: "blur",
          },
        ],
        price: [{ required: true, message: "请输入商品价格", trigger: "blur" }],
        market_price: [
          { required: true, message: "请输入市场价格", trigger: "blur" },
        ],
        first_cateid: [
          { required: true, message: "请选择一级分类", trigger: "change" },
        ],
        second_cateid: [
          { required: true, message: "请选择二级分类", trigger: "blur" },
        ],
        specsid: [
          { required: true, message: "请选择商品规格", trigger: "change" },
        ],
        specsattr: [
          { required: true, message: "请选择规格属性", trigger: "blur" },
        ],
      },
      //设置二级分类数据
      secondArr: [],
      //规格属性
      specsArr: [],
    }
  },
  mounted() {
    // 组件一加载调用分类列表接口
    this.getCate(),
      // 组件一加载调用规格属性接口
      this.getSpecs()
  },
  computed: {
    ...mapGetters({
      catelist: "cate/getCateList",
      specslist: "specs/getSpecsList"
    }),
  },
  methods: {
    ...mapActions({
      getCount: "goods/getCountAction",
      getGoodsList: "goods/getGoodsListAction",
      getCate: "cate/changeCateAction",
      getSpecs: "specs/getSpecsListAction"
    }),
    // 封装一个实例化富文本编辑器得到方法
    cateEdit(){
     console.log('打开弹框');
      //实例化插件
      this.edit = new wangEditor('#edit')
      //创建
      this.edit.create()
     //设置初始值
      this.edit.txt.html(this.goodsForm.description)
      console.log(this.edit,'编辑器');
    },
    // 封装一个切换一级分类的方法
    changeCate(n) {
      // console.log(n,'huixianl ');
      //思路就是用户选中数组的某一项跟双向数据绑定的值匹配，匹配成功找到下标索引，找到所在children
      let index = this.catelist.findIndex(
        (item) => item.id == this.goodsForm.first_cateid
      );
      console.log(index, 'index');
      this.secondArr = this.catelist[index].children
      //清空二级分类的双向数据绑定的值
      if (!n) {
        this.goodsForm.second_cateid = '';
      }
    },
    changeSpecs(n) {
      let index = this.specslist.findIndex((item) => item.id == this.goodsForm.specsid)
      this.specsArr = this.specslist[index].attrs;
      if (!n) {
        this.goodsForm.specsattr = '';
      }
    },
    //文件限制方法
    onExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length
        } 个文件`
      )
    },
    // 预览的回调函数
    onPreview(file) {
      console.log(file, "文件");
      //得到文件地址之后，把它赋值给要显示的属性
      this.dialogImageUrl = file.url;
      // 打开图片预览弹框
      this.dialogVisible = true
    },
    // 移除触发的钩子函数
    handleRemove(file, fileList) {
      console.log(file, '移除', fileList);
    },
    //文件发生变化触发的回调函数
    onChange(file, fileList) {
      console.log(file, "文件详情，change时候");
      //把文件详情赋值给图片地址
      this.goodsForm.img = file.raw;
    },
    // 取消
    cancel() {
      this.$emit('cancel', false);
      this.reset()
    },
    // 封装一个清空事件
    reset() {
      this.goodsForm = {
        first_cateid: "", //一级分类编号
        second_cateid: "", //二级分类编号
        goodsname: "", //商品名称
        price: "", //商品价格
        market_price: "", //市场价格
        img: "", //商品图片（文件）
        description: "", //商品描述
        specsid: "", //商品规格编号
        specsattr: "", //商品规格属性
        isnew: 1, //是否新品1是2不是
        ishot: 1, //是否热卖1是2不是
        status: 1, //状态1正常2禁用
      }
      // 调用清空验证的方法
      this.$refs.goodsForm.resetFields();
      this.fileList = [];
      // 当弹框关闭的时候，我们触发销毁
      this.edit.destroy()
    },
    // 封装一个查询一条信息的数据接口
    lookup(id) {
      goodsInfo({ id }).then((res) => {
        if (res.code == 200) {
          this.goodsForm = res.list;
          // 把商品描述的值赋值给编辑器
          this.edit.txt.html(this.goodsForm.description)
          //对图片进行数据回显
          this.fileList = this.goodsForm.img
            ? [{ url: this.goodsForm.img }]
            : [];
          this.goodsForm.id = id;
          //针对于规格属性进行结构转化
          this.goodsForm.specsattr = this.goodsForm.specsattr.split(',')
          //重新调用change事件 目的实现 label的渲染
          this.changeCate(true);
          this.changeSpecs(true);
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    // 封装一个确定事件
    confirm() {
      this.$refs.goodsForm.validate((val) => {
        if (val) {
          this.goodsForm.specsattr = this.goodsForm.specsattr ?
            this.goodsForm.specsattr.join(",") : "";
            // 给商品描述赋值
            this.goodsForm.description = this.edit.txt.html()
          if (this.isAdd) {
            // console.log(this.goodsForm, '商品表单对象');
            goodsAdd(this.goodsForm).then((res) => {
              // console.log(res, '商品管理添加');
              if (res.code == 200) {
                this.$message.success(res.msg);
                this.cancel();
                this.getCount();
                this.getGoodsList()
              } else {
                this.$message.error(res.msg)
              }
            })
          } else {
            // console.log('编辑接口');
            goodsEdit(this.goodsForm).then((res) => {
              // console.log(res, '商品管理添加');
              if (res.code == 200) {
                this.$message.success(res.msg);
                this.cancel();
                this.getCount();
                this.getGoodsList()
              } else {
                this.$message.error(res.msg)
              }
            })
          }
        } else {
          this.$message.error("验证失败");
          return false
        }
      })
    },
  },

}
</script>
<style lang="">
    
</style>